package middleware

import (
	"github.com/gin-gonic/gin"
	"inspector/pkg/code"
	"inspector/pkg/errors"
	"inspector/pkg/result"
)

func ErrorHandler() gin.HandlerFunc {
	return func(c *gin.Context) {
		c.Next()

		if len(c.Errors) > 0 {
			err := c.Errors[0].Err
			var e *errors.Error
			switch {
			case errors.As(err, &e):
				result.SendResponse(c, nil, e)
			default:
				result.SendResponse(c, nil, errors.New(code.NewErrInternalServer(), err.Error()))
			}
			c.Abort()
			return
		}
	}
}
